package com.yunlongn.common.core.utils.collection;


import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 * default
 * @date 2020/11/19 15:38
 * @author yunlongn
 */
public class CollectionUtils {

    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    public static <T> Set<T> asSet(T... objs) {
        return new HashSet<>(Arrays.asList(objs));
    }

    public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
        Set<U> set = from.stream().map(func).collect(Collectors.toSet());
        set.removeAll(Collections.singleton(null));
        return new ArrayList<>(set);
    }

    public static <T, U> Set<U> convertSet(List<T> from, Function<T, U> func) {
        return from.stream().map(func).collect(Collectors.toSet());
    }

    public static <T, K, V> Map<K, V> convertMap(List<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {
        return from.stream().collect(Collectors.toMap(keyFunc, valueFunc));
    }

    public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc) {
        return from.stream().collect(Collectors.toMap(keyFunc, Function.identity(), (oldValue,newValue)-> newValue ));
    }


    public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
        return org.springframework.util.CollectionUtils.containsAny(source, candidates);
    }

    /**
     * 切割list工具类
     * @author Yun
     * @since  2020/09/09
     **/
    public static <T> List<List<T>> divide(List<T>origin , int size){
//        divide(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 3)
        int block = (origin.size() + size - 1) / size;
        return IntStream.range(0,block).
                boxed().map(i->{
            int start = i*size;
            int end = Math.min(start + size,origin.size());
            return origin.subList(start,end);
        }).collect(Collectors.toList());
    }

}

